package com.wcgksoft.controller.addserviceorder;


import com.wcgksoft.common.util.Layui;
import com.wcgksoft.entity.admin.Account;
import com.wcgksoft.entity.goods.AddService;
import com.wcgksoft.entity.goods.Goods;
import com.wcgksoft.entity.order.AddServiceOrder;
import com.wcgksoft.entity.order.AddServiceOrderDetails;
import com.wcgksoft.entity.order.OrderDetails;
import com.wcgksoft.entity.system.SysUser;
import com.wcgksoft.service.goods.AddServiceService;
import com.wcgksoft.service.goods.GoodsService;
import com.wcgksoft.service.order.AddServiceOrderService;
import com.wcgksoft.service.order.OrderService;
import com.wcgksoft.service.system.UserService;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Random;

/**
 * @author 御风
 * @version V1.0
 * @Package com.wcgksoft.controller.goods
 * @Description 购物订单
 * @date 2020/5/12 16:11
 * @ClassName GoodsController
 */
@Controller
@RequestMapping("purchaseserviceorder/list")
public class purchaseserviceorderController {

  @Autowired
  private AddServiceService addServiceService;
  @Autowired
  private AddServiceOrderService orderService;
@Autowired
private UserService userService;

  @ResponseBody
  @RequestMapping(value = "findallorder")
  public Layui findallorder(@RequestParam(value = "page", required = false) Integer page,
                            @RequestParam(value = "limit", required = false) Integer limit,
                            @RequestParam(value = "status", required = false) Integer status) {

    DetachedCriteria criteria = DetachedCriteria.forClass(AddServiceOrder.class);
    if (null != status) {
      criteria.add(Restrictions.eq("status", status));
    }
    Account account = (Account) SecurityUtils.getSubject().getSession().getAttribute("om_user");
    if (account.getAuthority().getRoleCode().equals("saleMan")) {
      criteria.add(Restrictions.eq("saleManId", account.getId()));
      criteria.add(Restrictions.eq("agentId", account.getAgent_id()));
    }else if(account.getAuthority().getRoleCode().equals("agent")){
      criteria.add(Restrictions.eq("agentId", account.getId()));
    }
    criteria.addOrder(Order.desc("buyTime"));
    List<AddServiceOrder> list = orderService.findByConditions(criteria, page, limit);
    return Layui.data(0, "查询成功", orderService.getTotalCount(), list);
  }

  @ResponseBody
  @RequestMapping(value = "find")
  public Layui findAll() {
    DetachedCriteria criteria = DetachedCriteria.forClass(AddService.class);
    List<AddService> list = addServiceService.findByConditions(criteria);
    return Layui.data(0, "查询成功", list);
  }

  @ResponseBody
  @RequestMapping(value = "findgood")
  public Layui findgood(@RequestParam(value = "gid", required = false) Integer gid) {
    AddService goods = addServiceService.findById(gid);
    return Layui.data(0, "查询成功", goods);
  }


  @ResponseBody
  @RequestMapping(value = "finduser")
  public Layui finduser() {
    DetachedCriteria detachedCriteria = DetachedCriteria.forClass(SysUser.class);
    Account account = (Account) SecurityUtils.getSubject().getSession().getAttribute("om_user");
    if (account.getAuthority().getRoleCode().equals("saleMan")) {
      detachedCriteria.add(Restrictions.eq("saleMan_id",account.getId()));
      detachedCriteria.add(Restrictions.eq("agent_id",account.getAgent_id()));
    }else if(account.getAuthority().getRoleCode().equals("agent")){
      detachedCriteria.add(Restrictions.eq("agent_id",account.getId()));
    }

    List<SysUser> sysUsers = userService.findByConditions(detachedCriteria);
    //AddService goods = addServiceService.findById(gid);
    return Layui.data(0, "查询成功", sysUsers);
  }


  @ResponseBody
  @RequestMapping(value = "update")
  public Layui update(HttpServletRequest request,
                      @RequestParam(value = "data", required = false) String data,
                      @RequestParam(value = "goods", required = false) Integer[] goods) throws Exception {
    JSONObject param = JSONObject.fromObject(data);
    if (param == null) {
      return Layui.data(1, "请求格式有误", 0, null);
    } else {
      AddServiceOrder order = (AddServiceOrder) JSONObject.toBean(JSONObject.fromObject(data), AddServiceOrder.class);
      int anInt = param.getInt("userid");
      SysUser sysUser = userService.findById(anInt);
      order.setSysUser(sysUser);
      order.setOrderNo(getOrderIdByTime());
      Account account = (Account) SecurityUtils.getSubject().getSession().getAttribute("om_user");
      if (account.getAuthority().getRoleCode().equals("saleMan")) {
        order.setAgentId(account.getAgent_id());
        order.setSaleManId(account.getId());
      }else if(account.getAuthority().getRoleCode().equals("agent")){
        order.setAgentId(account.getId());
        order.setSaleManId(account.getId());
      }
      order.setBuyTime(new Date());
      order.setStatus(1);
      order.setDeletetype(0);
      order.setAccountname(account.getName());
      HashSet<AddServiceOrderDetails> details1 = new HashSet<>();
      for (int i = 0; i < goods.length; i++) {
        AddServiceOrderDetails details = new AddServiceOrderDetails();
        details.setAdd_id(goods[i]);
        details.setAddService(addServiceService.findById(goods[i]));
        details.setAddServiceOrder(order);
        details.setNumbers(1);
        details1.add(details);
      }

      order.setDetailsSet(details1);
      orderService.saveOrUpdate(order);
      return Layui.data(0, "保存成功", 1, Layui.addList(order));
    }
  }

  /**
   * 删除
   *
   * @param id
   * @param
   * @return
   */
  @ResponseBody
  @RequestMapping(value = "delete")
  @Transactional
  public Layui delete(@RequestParam(value = "id") Integer id) {
    System.out.println("id" + id);
    AddServiceOrder byId = orderService.findById(id);
    byId.setDeletetype(1);
    orderService.saveMerge(byId);

    return Layui.data(1, "删除成功", 1, null);
  }

  public static String getOrderIdByTime() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    String newDate = sdf.format(new Date());
    String result = "";
    Random random = new Random();
    for (int i = 0; i < 3; i++) {
      result += random.nextInt(10);
    }
    return newDate + result;
  }
}
